
<template>
  <div>
    <el-table
      :data="tableDisplayData"
      id="chartTableExpand"
      style="width: 100%"
      ref="chartTable"
      @expand-change="handleRowClick"
      :expand-row-keys="expandedRows"
      :row-key="getRowKeys"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table
            :ref="'expandTable' + scope.row.id"
            :data="scope.row.tableExpandData"
            style="width: 100%"
            v-loading="expandLoading"
            @selection-change="
              (val) => {
                return handleExpandSelectionChange(val, scope.row.id);
              }
            "
          >
            <el-table-column
              :selectable="
                (row) => {
                  return checkSelectable(row, 'id');
                }
              "
              type="selection"
            >
            </el-table-column>
            <el-table-column
              prop="className"
              label="班级名称"
              width="180"
              fixed="left"
            >
              <template slot-scope="scope">
                <span>
                  {{ scope.row.Name }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="studentCount" label="学生数量">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.StudentCount }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="answerCount" label="回答数量">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.AnswerCount }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="schoolName" label="学校名">
        <template slot-scope="scope">
          <span>
            {{ scope.row.schoolName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="classCount" label="班级数量">
        <template slot-scope="scope">
          <span>
            {{ scope.row.classCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="时间">
        <template slot-scope="scope">
          <span>
            {{ scope.row.date }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="search">
        <template slot="header" slot-scope="scope">
          <el-input v-model="searchKey" size="medium" placeholder="Search" />
        </template>
        <template slot-scope="scope"> </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getClassData, getSchoolData } from "@/api/api";
export default {
  name: "embededTable",
  props: {
    tooltip: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      multipleSelection: [],
      selections: [],
      banNumber: 5,
      isTableSelected: false,
      tableExpandData: [],
      filterTableData: [],
      searchKey: "",
      tableDisplayData: [],
      isClassTableExpanded: false,
      expandedRows: [],
      expandLoading: false,
    };
  },
  async created() {
    let _this = this;
    await _this.getData();
  },
  mounted() {
    let _this = this;
  },
  watch: {
    searchKey: function (val) {
      this.tableDisplayData = this.filterTableData.filter(function (data) {
        return data.schoolName.toLowerCase().includes(val.toLowerCase());
      });
    },
  },

  components: {},
  methods: {
    getRowKeys: function (row) {
      return row.id;
    },
    async getClassList(id) {
      let _this = this;
      await getClassData(id)
        .then((res) => {
          _this.tableExpandData = res;
        })
        .catch((err) => {
          console.log(err, "err");
        });
    },
    async getSchoolList() {
      let _this = this;
      await getSchoolData()
        .then((res) => {
          _this.tableData = res;
          _this.filterTableData = _this.tableData;
          _this.tableDisplayData = _this.tableData;
        })
        .catch((err) => {
          console.log(err, "err");
        });
    },
    async getData() {
      let _this = this;
      await _this.getSchoolList();
    },

    // 点击展开
     handleRowClick(row,rows) {
      let _this = this;

      _this.getExpandClassData(row,rows);
    },

    // 获取学校或班级汇总数据
    async getExpandClassData(row,rows) {
      let _this = this;
      let schoolId = row.id
      // 展开class table对应的ref
      let expandTable = "expandTable" + schoolId;

      // table展开时，根据之前选中的选项通过toggleRowSelection点击checkbox
      _this.$nextTick(function () {
        if (_this.$refs[expandTable]) {
          let hasSelections =
            _this.selections.length > 0 ||
            _this.selections[schoolId] ||
            (_this.selections[schoolId]
              ? _this.selections[schoolId].length
              : undefined) > 0;
          if (hasSelections) {
            _this.isClassTableExpanded = true;
            let selectedIds = _this.selections[schoolId].map(
              (mSelect) => mSelect.id
            );
            row.tableExpandData.forEach((row) => {
              if (selectedIds.includes(row.id)) {
                _this.$refs[expandTable].toggleRowSelection(row, true);
              }
            });
          }
        }
        _this.isClassTableExpanded = false;
      });
      const delIndex = _this.expandedRows.findIndex((item)=>{return item === schoolId});
      if (delIndex > -1) {
        _this.expandedRows.splice(delIndex, 1);
      }
      
      const isRowNowExpand = rows.some(r => r.id === row.id) // 判断当前行展开状态
      if (isRowNowExpand) {
          _this.expandedRows = [schoolId,..._this.expandedRows];
      }
      console.log(_this.expandedRows)

      // 如果已经展开获取或数据了，就返回不要再获取了
      if (row.isExpanded) {
        return;
      }
      _this.expandLoading = true;
      await _this.getClassList(row.id);

      // 将school下对应的class表格数据，赋值到相应的school下
      // 作为tableExpandData存起来

      // row.tableExpandData = _this.tableExpandData;
      // row.isExpanded = true;
      _this.$nextTick(() => {
        _this.$set(row, "tableExpandData", _this.tableExpandData);
        _this.$set(row, "isExpanded", true);
        // _this.expandedRows = [schoolId,..._this.expandedRows];
        _this.expandLoading = false;
      });
    },

    // 单选
    handleExpandSelectionChange(val, tableId) {
      let _this = this;
      // 如果是表格展开时去点击的话，就不要改变selections的值
      if (!_this.isClassTableExpanded) {
        // 这里将 multipleSelection的值对应相应的table存起来
        // 也就是说一个table 对应它自己的 multipleSelection
        // 键是tableId 值是 multipleSelection
        _this.selections[tableId] = val;
      }
      _this.updateMultipleSelection();
    },

    updateMultipleSelection() {
      let _this = this;
      // 把selections里的row取出来汇总
      _this.multipleSelection = [].concat.apply(
        [],
        Object.keys(_this.selections).map(function (key) {
          return _this.selections[key];
        })
      );
    },

    // 是否禁用多选
    checkSelectable: function (row, key) {
      let _this = this;
      let flag = true;
      // 多选最多选 banNumber 个
      if (_this.multipleSelection.length >= _this.banNumber) {
        if (!Array.isArray(row)) {
          flag = _this.multipleSelection.some(
            (selection) => row[key] === selection[key]
          );
        }
      }
      return flag;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
/* 去掉全选按钮 */
.el-table__fixed-header-wrapper .el-table__header th .el-checkbox .el-checkbox__input .el-checkbox__inner{
  display: none;
}
</style>